package com.black.web.app;

import com.black.app.domain.req.SmsReq;
import com.black.common.constant.CacheConstants;
import com.black.common.core.controller.BaseController;
import com.black.common.core.domain.R;
import com.black.common.core.domain.req.AppLoginReq;
import com.black.common.core.domain.resp.AppUserDetails;
import com.black.common.utils.SecurityUtils;
import com.black.framework.web.service.AppLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Api(tags = "app-登录相关Api")
@RestController
@RequestMapping("/app")
public class AppLoginController extends BaseController {

    @Autowired
    private AppLoginService appLoginService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R<String> login(@Valid @RequestBody AppLoginReq req) {
        String token = this.appLoginService.login(req);
        return R.ok(token);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("getInfo")
    public R<AppUserDetails> getInfo() {
        // 获取用户信息
        AppUserDetails loginUser = SecurityUtils.getAppLoginUser();

        return R.ok(loginUser);
    }


    /**
     * 发送验证码
     *
     * @return
     */
    @ApiOperation(value = "发送短信验证码")
    @PostMapping("/sendSms")
    public R<Map<String, Object>> sendSms(@RequestBody @Valid SmsReq req) {
        //1、判断redis是否存在验证码，如果存在，则提示用户已发送过验证码，请勿重复发送
        String redisKey = "";
        if (req.getType() == 1) {
            // 登录
            redisKey = CacheConstants.SMS_LOGIN_CODE_KEY + req.getPhone();
        } else {
            // 注册
            redisKey = CacheConstants.SMS_REGISTER_CODE_KEY + req.getPhone();
        }

        if (redisTemplate.hasKey(redisKey)) {
            return R.fail("请勿重复发送验证码");
        }
        int expireTime = 2;

        String code = new Random().nextInt(9000) + 1000 + "";

        //调用 云短信发送的功能

        this.redisTemplate.opsForValue().set(redisKey, code, expireTime, TimeUnit.MINUTES);


        Map<String, Object> result = new HashMap<>();
        result.put("expired", expireTime * 60);

        return R.ok(result);
    }
}
